package deployr.core;

import static java.text.MessageFormat.*;

import java.io.*;

import deployr.domain.*;

public class Deploy {

	private WebApp webapp;
	private String webappId;
	private DeployListener deployListener;

	public Deploy(FileSystem assets, IProject project) {
		webappId = id(project);
		webapp = new WebAppBuilder().add(checksum(project)).newWebApp(assets.getFile());
	}

	public Deploy(FileSystem assets, IUpdate update) {
		webappId = id(update);
		webapp = new WebAppBuilder().add(checksum(update)).newWebApp(assets.getFile());
	}

	private String id(IUpdate update) {
		return format("{0}-{1}u{2}", update.getArtifactId(), update.getVersion(), update.index());
	}

	private Checksum checksum(IProject project) {
		return new ChecksumBuilder(project.getChecksum()).checksum();
	}

	private Checksum checksum(IUpdate update) {
		return new ChecksumBuilder(update.getChecksum()).checksum();
	}

	public String id(IProject project) {
		return format("{0}-{1}", project.getArtifactId(), project.getVersion());
	}

	public void webappTo(FileSystem webapps) {
		webapps.mkdirs(webappId);
		File deployable = new File(webapps.getFile(), webappId);
		webapp.copyTo(deployable);
		willDeploy(webappId);
	}

	public void warTo(FileSystem webapps) {
		File deployable = new File(webapps.getFile(), format("{0}.war", webappId));
		webapp.zipTo(deployable);
		willDeploy(webappId);
	}

	private void willDeploy(String appId) {
		if (null != deployListener)
			deployListener.willDeploy(appId);
	}

	public void attach(DeployListener deployListener) {
		this.deployListener = deployListener;
	}

}